package com.cx.service.impl;

import com.cx.mapper.MenuMapper;
import com.cx.mapper.UserMapper;
import com.cx.pojo.LoginUserDetails;
import com.cx.pojo.User;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;


@Service
@RequiredArgsConstructor
public class UserDetailsServiceImpl implements UserDetailsService {
    private final UserMapper userMapper;
    private final MenuMapper menuMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 这里SpringSecurity会自动调用passwordEncoder.matches()进行验证
        User user = userMapper.selectUserByUsername(username);
        if (Objects.isNull(user)) {
            //账号不存在
            throw new UsernameNotFoundException("用户不存在");
        }
        //  根据用户id获取数据库中的用户权限信息
        List<String> authorities = menuMapper.getAuthorities(user.getId());
        return new LoginUserDetails(user, authorities);
    }
}
